<!--
  用户管理-企业用户-简历管理
 -->
<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="简历列表" name="1">
        <!-- 搜索工作栏 -->
        <el-form
          ref="leftQueryParams"
          :model="leftQueryParams"
          size="small"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="姓名" prop="studentName">
            <el-input
              v-model="leftQueryParams.studentName"
              clearable
              placeholder="请输入姓名"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="leftQueryParams.sex"
              placeholder="请选择性别"
              clearable
              size="small"
            >
              <el-option label="不限" value="" />
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="leftQueryParams.startDate"
              type="number"
              style="width: 120px"
              placeholder="岁"
            />
            至
            <el-input
              v-model="leftQueryParams.endDate"
              type="number"
              style="width: 120px"
              placeholder="岁"
            />
          </el-form-item>
          <el-form-item label="居住地" prop="liveCity">
            <el-cascader
              v-model="leftQueryParams.liveCity"
              :show-all-levels="false"
              :options="provinceAndCityData"
              :props="{ value: 'label' }"
              placeholder="请选择城市"
            />
          </el-form-item>

          <el-form-item label="技能" prop="specialtyAbility">
            <el-input
              v-model="leftQueryParams.specialtyAbility"
              placeholder="请输入技能"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="语种" prop="languageAbility">
            <el-input
              v-model="leftQueryParams.languageAbility"
              placeholder="请输入语种"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="课程" prop="courses">
            <el-input
              v-model="leftQueryParams.courses"
              placeholder="请输入课程"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item
            label-width="120px"
            label="学校/学历/专业"
            prop="educationalExperience"
          >
            <el-input
              v-model="leftQueryParams.educationalExperience"
              placeholder="支持模糊匹配"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-refresh"
              @click="resetQuery"
            >重置</el-button>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
            >搜索</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="16">
            <el-button
              v-if="isSuperAdmin"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="exportDate()"
            >导出简历信息</el-button>
          </el-col>
        </el-row>
        <!-- 列表 -->
        <el-table v-loading="loading" :data="leftList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="学生姓名" align="center" prop="studentName" />
          <el-table-column label="手机号" align="center" prop="phoneNumber" />
          <el-table-column label="学校" align="center" prop="schoolName" />
          <el-table-column label="性别" align="center" prop="sex" />
          <el-table-column label="所学专业" align="center" prop="major" />
          <el-table-column label="居住地" align="center" prop="liveCity" />
          <el-table-column label="学历" align="center" prop="education" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="openResume(scope.row)"
              >查看简历</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >编辑简历</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handlePush(scope.row, false)"
              >人才推荐</el-button>
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="leftTotal > 0"
          :total="leftTotal"
          :page.sync="leftQueryParams.pageNo"
          :limit.sync="leftQueryParams.pageSize"
          @pagination="leftGetList"
        />
      </el-tab-pane>
      <el-tab-pane label="推送历史" name="3">
        <!-- 搜索工作栏 -->
        <el-form
          ref="rightQueryForm"
          :model="rightQueryParams"
          size="small"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="学生姓名" prop="studentName">
            <el-input
              v-model="rightQueryParams.studentName"
              placeholder="请输入学生姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="企业名称" prop="companyName">
            <el-input
              v-model="rightQueryParams.companyName"
              placeholder="请输入企业名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="职位" prop="jobName">
            <el-input
              v-model="rightQueryParams.jobName"
              placeholder="请输入职位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="操作人" prop="publisherName">
            <el-input
              v-model="rightQueryParams.publisherName"
              placeholder="请输入操作人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-refresh"
              @click="resetQuery"
            >重置</el-button>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
            >搜索</el-button>
          </el-form-item>
        </el-form>
        <!-- 列表 -->
        <el-table v-loading="loading" :data="rightList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="学生姓名" align="center" prop="studentName" />
          <el-table-column label="手机号" align="center" prop="phoneNumber" />
          <el-table-column label="学校" align="center" prop="schoolName" />
          <el-table-column label="所学专业" align="center" prop="major" />
          <el-table-column label="推送企业" align="center" prop="companyName" />
          <el-table-column label="推送职位" align="center" prop="jobName" />
          <el-table-column
            label="推送时间"
            align="center"
            prop="postDate"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ moment(scope.row.postDate).format("yyyy-MM-DD") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作人" align="center" prop="publisherName" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="openPushReason(scope.row)"
              >查看推荐理由</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="rightTotal > 0"
          :total="rightTotal"
          :page.sync="rightQueryParams.pageNo"
          :limit.sync="rightQueryParams.pageSize"
          @pagination="rightGetList"
        />
      </el-tab-pane>
    </el-tabs>
    <!-- 人才推荐 -->
    <el-dialog
      title="人才推荐"
      :visible.sync="pushPersonDialog"
      width="500px"
      append-to-body
    >
      <el-form ref="recommendForm" :model="recommendForm" label-width="80px">
        <el-form-item
          label="推送企业"
          prop="currenCompany"
          :rules="{ required: true, message: '企业必填', trigger: ['change'] }"
        >
          <el-select
            v-model="recommendForm.currenCompany"
            @change="fetchJobByCompany"
          >
            <el-option
              v-for="(item, index) in authedCompanyList"
              :key="index"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="职位"
          prop="currentJob"
          :rules="{ required: true, message: '职位必填', trigger: ['change'] }"
        >
          <el-select v-model="recommendForm.currentJob">
            <el-option
              v-for="(item, index) in jobList"
              :key="index"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="简历模板"
          prop="studentCurriculumVitaeId"
          :rules="{ required: true, message: '简历模板必选', trigger: ['change'] }"
        >
          <el-select v-model="recommendForm.studentCurriculumVitaeId">
            <el-option v-for="(item,index) in resumeList" :key="index" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="推荐原因" prop="remark">
          <el-input
            v-model="recommendForm.remark"
            type="textarea"
            :maxlength="500"
            show-word-limit
            :autosize="{ minRows: 4, maxRows: 6 }"
          />
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button
          size="mini"
          type="text"
          @click="openResume(null)"
        >点击查看学生简历</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pushPersonDialog = false">取 消</el-button>
        <el-button type="primary" @click="finishPush">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 简历预览 -->
    <el-dialog title="简历预览" :visible.sync="resumeDialog" width="1100px">
      <ResumeReview v-if="resumeDialog" ref="ResumeReview" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="resumeDialog = false">关闭</el-button>
        <el-button type="primary" @click="openResumeEdit">编辑</el-button>
        <!-- <el-button type="primary" @click="handlePush(null)">人才推荐</el-button> -->
      </span>
    </el-dialog>
    <!-- 简历编辑 -->
    <el-dialog title="简历编辑" :visible.sync="resumeEditDialog" width="1100px">
      <resumeEdit ref="resumeEdit" @updateEnd="resumeEditDialog = false" />
    </el-dialog>
  </div>
</template>

<script>
import {
  getAuthedCompany,
  getJobWaitExamineList,
  sendStudentRecommend,
  checkResumeFromJob
} from '@/api/school-admin-api/hireManage'
import {
  getUserResume,
  getStudentResume
} from '@/api/school-admin-api/userManage/student/index.js'
import businessAreaData from '@/utils/businessAreaData.js'
import { deepClone } from '@/utils/index'
import ResumeReview from '@/components/resumeReview/index.vue'
import resumeEdit from './resumeEdit.vue'
import { provinceAndCityData } from '@/utils/frontDataDict.js'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { exportStudentCurriculum } from '@/api/company-admin-api/hireManage/index.js'
export default {
  name: 'Company',
  components: {
    ResumeReview,
    resumeEdit
  },
  data() {
    return {
      moment: moment,
      provinceAndCityData: provinceAndCityData,
      recommendForm: {
        currenCompany: '',
        currentJob: '',
        remark: '',
        studentCurriculumVitaeId: null
      },
      resumeList: [],
      resumeEditDialog: false,
      resumeDialog: false,
      mutilInputText: '',
      inputText: '', // 当前输入属性值
      pushPersonDialog: false, // 推送简历弹窗
      checkResult: '1',
      activeName: '1',
      // 企业行业类型数据，二级联动
      businessAreaData: businessAreaData,
      // 遮罩层
      loading: true,
      // 待审核-总条数
      leftTotal: 0,
      // 已审核-总条数
      rightTotal: 0,
      // 企业管理列表
      leftList: [],
      // 已审核企业列表
      rightList: [],
      // 弹出层标题
      title: '',
      leftQueryParams: {
        pageNo: 1,
        pageSize: 10,
        studentName: '',
        sex: '', // 性别
        startDate: '', // 年龄起始日期
        endDate: '', // 年龄结束日期
        liveCity: [], // 居住地
        languageAbility: '', // 语种
        courses: '', // 已修课程
        specialtyAbility: '', // 专业技能
        educationalExperience: '' // 学校/学历/专业 模糊匹配
      },
      rightQueryParams: {
        pageNo: 1,
        pageSize: 10,
        studentName: '', // 学生名称
        companyName: '', // 企业名称
        jobName: '', // 职位名称
        sendType: '2', // 最新字段， 0 学生自主投递 1 企业直接发送邀请 2 平台运营邀请（这里传0，过滤掉企业发起的邀请）
        publisherName: '' // 发布人名称（创建人）
      },
      // 当前审核数据
      currentCheckRow: null,
      authedCompanyList: [], // 已认证，且有企业介绍的企业列表
      jobList: [] // 企业下的职位列表
    }
  },
  computed: {
    ...mapGetters(['roles']),
    isSuperAdmin() {
      return (
        Array.isArray(this.roles) && this.roles.indexOf('super_admin') > -1
      )
    }
  },
  watch: {
    pushPersonDialog: function(newValue) {
      !newValue && this.$refs['recommendForm'].resetFields()
    }
  },
  created() {
    this.getAuthedCompany()
    this.leftGetList()
    this.rightGetList()
  },
  methods: {
    exportDate() {
      const params = JSON.parse(JSON.stringify(this.leftQueryParams))
      if (Array.isArray(params.liveCity) && params.liveCity.length === 2) {
        params.liveCity = params.liveCity[1]
      } else {
        delete params.liveCity
      }
      exportStudentCurriculum(params).then((response) => {
        this.$download.excel(response, '简历信息.xls')
      })
    },
    // 获取认证后的企业列表
    getAuthedCompany() {
      getAuthedCompany().then((res) => {
        if (res.code === 0 && res.data) {
          this.authedCompanyList = res.data.map((item) => {
            return {
              value: item.id,
              label: item.companyName
            }
          })
          if (this.authedCompanyList.length) {
            this.recommendForm.currenCompany = this.authedCompanyList[0].value
            this.fetchJobByCompany()
          } else {
            this.recommendForm.currenCompany = ''
          }
        }
      })
    },
    fetchJobByCompany() {
      const params = {
        pageNo: 1,
        pageSize: 999,
        companyId: this.recommendForm.currenCompany,
        flag: ['2'] // 职位状态 jobHireStatus (string)：0 未发布，1 待审核，2 发布中，3 暂停发布, 4 驳回
      }
      getJobWaitExamineList(params).then((res) => {
        if (res.code === 0 && res.data) {
          this.jobList = res.data.list.map((item) => {
            return {
              label: item.jobName,
              value: item.id
            }
          })
          if (this.jobList.length) {
            this.recommendForm.currentJob = this.jobList[0].value
          } else {
            this.recommendForm.currentJob = ''
          }
        }
      })
    },
    // 提交简历编辑
    submitResumeEdit() {
      console.log('提交简历编辑')
      this.resumeEditDialog = false
    },
    // 打开简历编辑
    openResumeEdit() {
      this.handleUpdate(this.currentRow)
    },
    // 打开当前简历
    openResume(row) {
      let flag = false
      if (row) {
        this.currentRow = deepClone(row)
      } else {
        row = this.currentRow
        flag = true
      }
      getStudentResume({ studentId: this.currentRow.studentId }).then((res) => {
        if (
          res.code === 0 &&
          res.data &&
          res.data.studentCurriculumVitaeRespVOList.length > 0
        ) {
          this.resumeDialog = true
          const {
            sex,
            clan,
            id,
            jobStatus,
            inJobTime,
            studentName,
            political,
            nativePlace,
            graduateTime,
            studentPictureUrl,
            birthday,
            liveCity,
            phoneNumber,
            email
          } = row
          const userInfo = {
            sex,
            clan,
            political,
            nativePlace,
            studentName,
            nickname: studentName,
            studentPictureUrl,
            birthday,
            id,
            liveCity,
            mobile: phoneNumber,
            phoneNumber,
            email,
            graduateTime,
            jobStatus,
            inJobTime
          }
          userInfo.jobStatus = res.data.jobStatus || '--'
          userInfo.inJobTime = res.data.inJobTime || '--'
          setTimeout(() => {
            this.$refs.ResumeReview.open(
              res.data.studentCurriculumVitaeRespVOList.filter(
                (v) => v.id == row.id
              )[0] || null,
              userInfo
            )
          }, 0)
        } else {
          this.$message.error('该学生未填写简历')
        }
      })
    },
    // 查看推荐理由
    openPushReason(row) {
      const reason = row?.remark || '--'
      this.$alert(reason, '推荐理由', {
        confirmButtonText: '确定'
      })
    },
    editModulesConfig(row) {
      console.log('修改属性内容、排序>>>', row)
      this.currentRow = deepClone(row)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    handleClick(data) {
      switch (this.activeName) {
        case '1':
          this.leftGetList()
          break
        case '3':
          this.rightGetList()
          break
        default:
          break
      }
    },
    // 返回年龄
    getAge(birthday) {
      // 出生时间 毫秒
      var birthDayTime = new Date(birthday).getTime()
      // 当前时间 毫秒
      var nowTime = new Date().getTime()
      // 一年毫秒数(365 * 86400000 = 31536000000)
      return Math.floor((nowTime - birthDayTime) / 31536000000)
    },
    // 简历列表
    leftGetList() {
      this.loading = true
      // 处理查询参数
      const params = JSON.parse(JSON.stringify(this.leftQueryParams))
      for (const key in params) {
        if (params[key] === '' || params[key] === null) {
          delete params[key]
        }
      }
      if (this.leftQueryParams.startDate) {
        const now = new Date().getTime()
        params.endDate = moment(
          now - 1000 * 60 * 60 * 24 * 365 * this.leftQueryParams.startDate
        ).format('yyyy-MM-DD')
      }
      if (this.leftQueryParams.endDate) {
        const now = new Date().getTime()
        params.startDate = moment(
          now - 1000 * 60 * 60 * 24 * 365 * this.leftQueryParams.endDate
        ).format('yyyy-MM-DD')
      }
      if (Array.isArray(params.liveCity) && params.liveCity.length === 2) {
        params.liveCity = params.liveCity[1]
      } else {
        delete params.liveCity
      }
      // 执行查询
      getUserResume(params).then((res) => {
        const list = deepClone(res.data.list).map((item) => {
          // item.birthday = this.getAge(item.birthday)
          // try {
          //   item.educationalExperience = JSON.parse(item.educationalExperience)
          // } catch (error) {
          //   console.error(new Error('教育经历不存在'))
          // }
          if (
            Array.isArray(item.educationalExperience) &&
            item.educationalExperience.length
          ) {
            const educate = ['大专', '本科', '硕士', '博士']
            educate.map((iten) => {
              const matchEducate = item.educationalExperience.find(
                (single) => single.educationalBackground.indexOf(iten) > -1
              )
              if (matchEducate) {
                item.schoolName = matchEducate.schoolName // 学校名称
                item.major = matchEducate.major // 专业
                item.education = iten // 学历
              }
            })
          } else {
            item.schoolName = '--' // 学校名称
            item.major = '--' // 专业
            item.education = '--' // 学历
          }
          return item
        })
        this.leftList = list
        this.leftTotal = res.data.total
        this.loading = false
      })
    },
    // 人才推荐历史
    rightGetList() {
      const params = { ...this.rightQueryParams }
      this.loading = true
      checkResumeFromJob(params)
        .then((res) => {
          if (res.code === 0) {
            const list = deepClone(res.data.list).map((item) => {
              // item.birthday = this.getAge(item.birthday)
              // try {
              //   item.educationalExperience = JSON.parse(item.educationalExperience)
              // } catch (error) {
              //   console.error(new Error('教育经历不存在'))
              // }
              if (
                Array.isArray(item.educationalExperience) &&
                item.educationalExperience.length
              ) {
                const educate = ['大专', '本科', '硕士', '博士']
                educate.map((iten) => {
                  const matchEducate = item.educationalExperience.find(
                    (single) => single.educationalBackground.indexOf(iten) > -1
                  )
                  if (matchEducate) {
                    item.schoolName = matchEducate.schoolName // 学校名称
                    item.major = matchEducate.major // 专业
                    item.education = iten // 学历
                  }
                })
              } else {
                item.schoolName = '--' // 学校名称
                item.major = '--' // 专业
                item.education = '--' // 学历
              }
              return item
            })
            this.rightList = list
            this.rightTotal = res.data.total
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.activeName === '1') {
        this.leftQueryParams.pageNo = 1
        this.leftGetList()
      } else {
        this.rightQueryParams.pageNo = 1
        this.rightGetList()
      }
    },
    // 重制搜索条件
    resetQuery() {
      if (this.activeName === '1') {
        this.resetForm('leftQueryParams')
        this.handleQuery()
      } else {
        this.resetForm('rightQueryForm')
        this.handleQuery()
      }
    },
    fetchResumeData(list) {
      if (!list || list.length <= 0) return []
      return list.map((item, index) => {
        return {
          label: item.name || `模板${index + 1}`,
          value: item.id
        }
      })
    },
    // 打开人才推荐弹窗
    handlePush(row) {
      if (row) {
        this.currentRow = deepClone(row)
      }
      this.pushPersonDialog = true
      // getStudentResume({ studentId: this.currentRow.studentId }).then(res => {
      //   if (res.code === 0 && res.data && res.data.studentCurriculumVitaeRespVOList.length > 0) {
      //     this.resumeList = this.fetchResumeData(res.data.studentCurriculumVitaeRespVOList)
      //     this.pushPersonDialog = true
      //   }else{
      //     this.$message.error('该学生未填写简历')
      //   }
      // })
    },
    // 提交人才推荐
    finishPush() {
      this.$refs.recommendForm.validate((boo) => {
        if (boo) {
          const companyName = this.authedCompanyList.find(
            (item) => item.value === this.recommendForm.currenCompany
          )?.label
          this.$confirm(
            `即将推送${this.currentRow.studentName}至${companyName}企业`
          )
            .then((_) => {
              const { currenCompany, currentJob, remark } = this.recommendForm
              const prames = {
                companyId: currenCompany,
                jobId: currentJob,
                studentCurriculumVitaeId: this.currentRow.id,
                remark
              }
              sendStudentRecommend(prames).then((res) => {
                if (res.code === 0 && res.data) {
                  this.$message.success('操作成功')
                  this.recommendForm.remark = ''
                }
                this.pushPersonDialog = false
              })
            })
            .catch((_) => {})
        }
      })
    },
    /** 编辑简历 */
    handleUpdate(row) {
      if (row) {
        this.currentRow = deepClone(row)
      }
      this.resumeEditDialog = true
      setTimeout(() => {
        this.$refs.resumeEdit.init(row.studentId, row.id)
      }, 0)
    },
    handleDelete(row) {
      this.$confirm(`确认删除吗？`)
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    editConfig(row) {
      console.log('编辑配置>>>')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/vars.scss";
.attr-row {
  position: relative;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  margin: 14px;
  cursor: pointer;
  .drag-icon {
    position: absolute;
    left: 7px;
    top: 50%;
    transform: translateY(-50%);
    display: block;
    width: 10px;
    height: 20px;
    background: url(/static/img/drag.f5a055f4.png) no-repeat center center /
      cover;
    margin-right: 14px;
  }
  &:hover .drag-icon {
    background: url("../../../assets/images/drag_hover.png") no-repeat center
      center / cover;
  }
  .drag-text {
    flex: 1;
    @include t14h22;
    background: $gray03;
    padding: 7px 30px 7px 24px;
  }
  .el-icon-delete {
    position: absolute;
    right: 7px;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
